﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Kinect;

namespace KinectMenagerNamespace
{
    public abstract class TimeDependentKinectGesturePart : KinectGesturePart
    {
        private bool firstUpdate = true;
        private DateTime startTime;
        private TimeSpan maxDuration;

        public TimeDependentKinectGesturePart()
            :this(TimeSpan.MaxValue)
        {
        }

        public TimeDependentKinectGesturePart(TimeSpan maxDuration)
        {
            this.maxDuration = maxDuration;
        }

        public GestureState Update(Skeleton skeleton)
        {
            if (firstUpdate)
            {
                startTime = DateTime.Now;
                firstUpdate = false;
            }

            if ((DateTime.Now - startTime) < maxDuration)
            {
                switch(TimeDependentUpdate(skeleton))
                {
                    case GestureState.Succes:
                    {
                        if (OnGesturePartSucces != null)
                        {
                            OnGesturePartSucces.Invoke();
                        }
                        firstUpdate = true;
                        return GestureState.Succes;
                    }
                    case GestureState.InProgress:
                    {
                        return GestureState.InProgress;
                    }
                    case GestureState.Fail:
                    {
                        if (OnGesturePartFail != null)
                        {
                            OnGesturePartFail.Invoke();
                        }
                        firstUpdate = true;
                        return GestureState.Fail;
                    }
                    default:
                    {
                        if (OnGesturePartFail != null)
                        {
                            OnGesturePartFail.Invoke();
                        }
                        firstUpdate = true;
                        return GestureState.Fail;
                    }
                }
            }
            else
            {
                if (OnGesturePartFail != null)
                {
                    OnGesturePartFail.Invoke();
                }
                firstUpdate = true;
                return GestureState.Fail;                
            }
        }

        public abstract GestureState TimeDependentUpdate(Skeleton skeleton);

        public event GesturePartHandler OnGesturePartFail = null;
        public event GesturePartHandler OnGesturePartSucces = null;
    }
}
